<template>
  <div class="body_detail page-miH page-bgBack">
    <a-row type="flex" justify="space-between" class="company">
      <a-col>
        <a-icon type="left" class="mg_r20" @click="$router.go(-1)" />
        {{ editor ? "分组详情" : "添加用工单位分组" }}
      </a-col>
      <a-col v-if="editor">
        <a-button class="mg_r20" @click="editorDetail">{{ disabled ? "编辑" : "取消" }}</a-button>
        <a-button @click="deleteComapny">删除分组</a-button>
      </a-col>
    </a-row>
    <a-form :form="form">
      <div class="base_detail">基本信息</div>
      <a-form-item :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }" label="用工单位分组名称">
        <a-input
          v-decorator="['name', { rules: [{ required: true, message: '用工单位分组名称必填' }] }]"
          :disabled="disabled"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }" label="上级分组">
        <a-tree-select
          v-decorator="['parentId']"
          :treeData="groupTree"
          :replaceFields="{ children: 'childList', title: 'name', key: 'id', value: 'id' }"
          :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
          :disabled="disabled"
          placeholder="请选择"
          @change="onTreeChange"
        />
      </a-form-item>
      <a-form-item :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }" label="分管单位">
        <a-button v-if="!disabled && !detail.isAllCompany" @click="select"> 请选择 </a-button>
        <!-- <a-switch
          v-model="detail.isAllCompany"
          :disabled="disabled"
          checked-children="全部"
          style="margin-left: 10px"
          un-checked-children="自选"
          @change="changeSwitch"
        /> -->
        <a-table v-show="showDetail && !detail.isAllCompany" class="mg_t10" :row-key="(d) => d.id" :data-source="detail.companyList">
          <a-table-column title="分管单位名称" data-index="name" />
          <a-table-column title="联系人" data-index="legalPerson" />
          <a-table-column title="手机号" data-index="telephone" />
        </a-table>
      </a-form-item>
      <a-form-item v-if="editor" :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }" label="管理员">
        <a-table class="mg_t10" :row-key="(d) => d.id" :data-source="detail.adminUserList">
          <a-table-column title="姓名" data-index="name" />
          <a-table-column title="手机号" data-index="phone" />
          <a-table-column title="角色" data-index="roleName" />
        </a-table>
      </a-form-item>
    </a-form>
    <a-button v-if="!disabled" class="mg_l72" type="primary" @click="sureData">确认</a-button>
    <a-modal v-model="visible" :width="660" title="分管单位" @ok="handleOk">
      <a-row type="flex" class="all-body">
        <a-col :span="11">
          <a-input-search placeholder="搜索分管单位" style="width: 100%" @search="onSearch" />
          <div class="unit-list" @click="allSelect"><a-icon type="folder" class="unit-icon" />全部</div>
          <a-divider class="mg_t5 mg_b5" />

          <ul class="unit-body">
            <li v-for="(item, j) in unitList" :key="j" class="unit-list" @click="selectItem(item, unitList)">
              <a-icon type="folder" class="unit-icon" />
              <span> {{ item.name }}</span>
              <a-icon v-show="item.select" class="unit-r-icon" type="check" />
            </li>
          </ul>
        </a-col>
        <span class="divider" />
        <a-col :span="11" class="mg_l10">
          <div>已选</div>
          <ul class="unit-r-body">
            <li v-for="(item, i) in chosdeUnitList" :key="i" class="unit-list">
              <a-icon type="folder" class="unit-icon" />
              <span> {{ item.name }}</span>
              <a-icon class="unit-r-icon" type="close" @click="deleteItem(item, chosdeUnitList)" />
            </li>
          </ul>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import { mapState, mapGetters } from "vuex";
export default {
  name: "CompanyManagement",
  components: {},
  data() {
    return {
      validate: "",
      form: this.$form.createForm(this),
      selects: false,
      unitList: [],
      copyList: [],
      chosdeUnitList: [],
      password: 123456,
      spare: {},
      detail: {
        id: "",
        name: "",
        address: "",
        companyList: [],
        groupCityList: [],
        hrUserVO: {
          id: "",
          name: "",
          phone: "",
          roleId: "",
          roleName: "",
          status: 0
        },
        isAllCity: false
      },
      // 编辑/添加
      editor: false,
      disabled: false,
      // 详情表格
      showDetail: false,
      visible: false,
      name: "",
      valueCity: "130100",
      tempTreeLevel: null
    };
  },
  computed: {
    ...mapGetters({ MNGLIST: "admin/MNGLIST" }),
    ...mapState(["hr", "site"]),
    groupTree() {
      return this.site.groupTree;
    },
    selectedCityCodes() {
      return this.detail.groupCityList.map((item) => item.cityCode);
    },
    selectedCityName() {
      return this.detail.groupCityList.map((item) => item.cityName);
    },
    cityValidateStatus() {
      return this.detail.groupCityList.length > 0 ? "" : "error";
    },
    cityValidateStatusHelp() {
      return this.detail.groupCityList.length > 0 || this.detail.isAllCity ? "" : "分管地区必须选择";
    },
    companyList() {
      return this.hr.companyList;
    }
  },

  created() {
    this.disabled = !!this.$route.query.id;
    this.editor = !!this.$route.query.id;
    this.showDetail = !!this.$route.query.id;
  },
  mounted() {
    if (this.editor) {
      this.getDetail();
    }
  },
  methods: {
    onTreeChange(p1, p2, p3) {
      this.tempTreeLevel = p3.triggerNode.dataRef.level + 1;
    },
    changeCitySwitch(e) {
      this.detail.groupCityList = [];
      this.detail.isAllCity = e;
    },
    changeSwitch(e) {
      this.detail.companyList = [];
      this.detail.isAllCompany = e;
      if (!e) {
        this.select();
      }
    },
    repeatName(name) {
      return this.MNGLIST.find((v) => v.name === name);
    },
    // 全选单位
    allSelect() {
      this.selects = !this.selects;
      this.unitList.forEach((v) => {
        v.select = this.selects;
      });
      if (this.selects) {
        this.chosdeUnitList = this.unitList;
      } else {
        this.chosdeUnitList = [];
      }
    },

    // 编辑
    editorDetail() {
      this.disabled = !this.disabled;
      if (this.disabled) {
        history.back();
      }
    },
    // 选择城市
    handelCity(value) {
      let list = value.item;
      list = list.map((item) => ({
        cityCode: item.value,
        cityName: item.label
      }));
      this.detail.groupCityList = list;
    },
    // 搜索部门
    onSearch(e) {
      if (e) {
        this.unitList = this.copyList.filter((v) => v.name.includes(e));
      } else {
        this.unitList = this.copyList;
      }
    },
    // 分管单位
    async select() {
      await this.$store.dispatch("onCompanyListUpdate");
      let data = this.companyList;
      const chosed = this.detail.companyList.map((v) => v.id);
      this.visible = true;
      data = data || [];
      this.copyList = [...data];
      this.unitList = data;
      this.chosdeUnitList = [];
      data.map((v, i) => {
        if (chosed.includes(v.id)) {
          v.select = true;
          this.chosdeUnitList.push(v);
        }
        return v;
      });
    },
    // 选择单位
    selectItem(item, arr) {
      arr.find((v) => {
        if (v.id === item.id) {
          v.select = !v.select;
        }
      });
      const keys = this.chosdeUnitList.map((v) => v.id);
      if (!keys.includes(item.id)) {
        this.chosdeUnitList.push(item);
      } else {
        arr.find((v) => {
          if (v.id === item.id) {
            v.select = false;
          }
        });
        this.chosdeUnitList = this.chosdeUnitList.filter((v) => v.id !== item.id);
      }
    },
    // 删除选中的
    deleteItem(item, arr) {
      item.select = false;
      this.chosdeUnitList = arr.filter((v) => v.select);
    },
    // 确定单位
    handleOk() {
      this.detail.companyList = this.chosdeUnitList;
      this.visible = false;
      this.showDetail = true;
    },
    // 删除公司
    deleteComapny() {
      this.$confirm({
        title: "确定删除该公司吗?",
        onOk: () => {
          this.$request({
            method: "DELETE",
            url: `/hr/api/v1/childrenCompany/deleteChildAndRelation/${this.$route.query.id}`
          });
          history.back();
        }
      });
    },
    // 查看详情
    async getDetail() {
      const { data } = await this.$request({
        url: `/hr/api/v1/childrenCompany/findChildAndRelation/${this.$route.query.id}`
      });

      data.companyList = data.companyList || [];
      data.hrUserVO = data.hrUserVO || {};
      data.groupCityList = data.groupCityList || [];
      this.detail = data;
      this.spare = { ...data };
      const { name, parentId } = data;
      this.form.setFieldsValue({
        name,
        parentId: parentId === "0" || !parentId ? undefined : parentId
      });
    },
    // 添加/修改子公司
    sureData() {
      this.form.validateFields((err, values) => {
        if (!err) {
          Object.keys(values).forEach((key) => {
            if (key === "parentId") {
              this.detail[key] = values[key] || "0";
              this.detail["level"] = this.tempTreeLevel || 1;
            } else {
              this.detail[key] = values[key];
            }
          });
          this.detail["sort"] = this.detail["sort"] || 0;

          const { name, groupCityList, hrUserVO } = this.detail;
          if (!name && !groupCityList.length && !hrUserVO.name) {
            return this.$notification["warn"]({ message: "信息不完整" });
          }
          if (!this.detail.companyId) {
            this.detail.companyId = this.hr.companyId;
          }
          this.detail.groupCityAddList = this.detail.groupCityList;
          this.detail.userDTO = this.detail.hrUserVO;
          this.detail.userDTO.password = this.password;
          this.detail.managedCompanyList = this.detail.companyList.map((v) => v.id);
          if (this.editor) {
            this.$request({
              method: "PUT",
              url: `/hr/api/v1/childrenCompany/updateChildAndRelation`,
              data: this.detail
            }).then(({ success }) => {
              if (success) {
                this.$notification["success"]({ message: "修改成功" });
                history.back();
              }
            });
          } else {
            this.$request({
              method: "POST",
              url: `/hr/api/v1/childrenCompany/saveChildAndRelation`,
              data: this.detail
            }).then(({ success }) => {
              if (success) {
                this.$notification["success"]({ message: "添加成功" });
                history.back();
              }
            });
          }
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
ul {
  padding: 0;
  margin: 0;
}
.body_detail {
  padding: 25px;
  .company {
    color: #333333;
    font-size: 16px;
  }
  .base_detail {
    height: 48px;
    line-height: 48px;
    padding-left: 24px;
    margin: 20px 0;
    background: rgba(250, 250, 250, 1);
  }
}
.all-body {
  overflow: hidden;
  .unit-body {
    max-height: 350px;
    overflow-y: scroll;
  }
  .unit-r-body {
    min-height: 400px;
    max-height: 400px;
    overflow-y: scroll;
  }
  .unit-list {
    padding: 5px 0;
    .unit-icon {
      color: #9e9891;
      margin-right: 5px;
    }
    .unit-r-icon {
      float: right;
      margin-right: 5px;
      transform: translateY(25%);
    }
  }
}

.divider {
  display: inline-flex;
  border: 1px solid #e8e8e8;
  margin: 0 9px;
  min-height: 0px;
}
.ant-switch {
  background: var(--primary);
}
</style>
